﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using YAPL.Language.Core.Types;

namespace YAPL.Language.Compiler.CodeGen.ReflectionEmitGenerator.AstGen {
	public class ReConditionalGenerator : ReExpressionGenerator {
		public ReConditionalGenerator(ReCodeGenerator generator) : base(generator) { }
		public override void Generate(Ast.Expression expr) {


			var conditional = (Ast.ConditionalExpression)expr;
			Generator.EmitExpression(conditional.Condition);

			var ilGen = Generator.Get<ILGenerator>(ReCodeGenerator.IL_GENERATOR_KEY);
			ilGen.Emit(OpCodes.Castclass, typeof(YAPLBoolean));
			var boolGetter = typeof(YAPLBoolean).GetProperty("BoolValue").GetGetMethod();
			ilGen.Emit(OpCodes.Callvirt, boolGetter);
			var elseLabel = ilGen.DefineLabel();


			ilGen.Emit(OpCodes.Brfalse, elseLabel);

			Generator.EmitExpression(conditional.ThenBlock);

			var afterElseLabel = ilGen.DefineLabel();
			if (conditional.ElseBlock != null)
				ilGen.Emit(OpCodes.Br, afterElseLabel);

			ilGen.MarkLabel(elseLabel);
			if (conditional.ElseBlock != null) {
				Generator.EmitExpression(conditional.ElseBlock);
				ilGen.MarkLabel(afterElseLabel);
			}

			ilGen.Emit(OpCodes.Ldnull); //TODO Change to something meaningful
		}
	}
}
